﻿/*
创建人：longb
日期：2022-07-11
描述：材料申领单js
*/
var page = {
    pagetotal: 0,
    pageSize: 20,
    pageNumber: 1,
    ajaxUrl: getRootPath() + "/Ashx/ZsHandler/ZSNotProductMaterialApplyBillHandler.ashx",
    //初始化页面
    init: function () {
        page.bind();
        customizedEasyuiPagination('pp'); //定制化分页
    },
    //页面事件绑定
    bind: function () {
        var yearmonth=[];
        for(var i=new Date().getFullYear();i>=new Date().getFullYear()-5;i--){
            yearmonth.push({id:i,text:i});
        }
        $('#yearmonth,#year').combobox({
            data: yearmonth,
            valueField: 'id',
            textField: 'text',
        });
        var month=[];
        for(var i=1;i<=12;i++){month.push({id:i,text:i});}
        $('#month').combobox({
            data: month,
            valueField: 'id',
            textField: 'text',
        });
        page.post({action:"GetWorkcenterByFactory"}, function (res) {
            page.InitWorkcenterCombox(res,'#WorkcenterID');
            page.InitWorkcenterCombox(res,'#WorkcenterIDD');
        });
        $('#AuxMaterial').newselectCombox({
            search: function (obj) { },
            cancel: function (obj) { $('#AUXMATERIALID').val('');},
            selected: function (val, text,record,obj){
                $('#AUXMATERIALID').val(val);
                $('#txtCombox'+obj.index).textbox('setValue',text);
                $('#divComboxTxt'+obj.index).show();
                $('#divComboxSelect'+obj.index).hide(); 
            }
        },{},{url:page.ajaxUrl,action:"GetAuxMaterial",index:1});
        //申领单信息
        $("#yearTable").datagrid({
            checkOnSelect: false,
            selectOnCheck: false,
            singleSelect: true,
            rownumbers: true,
            onLoadSuccess: function (data) {
                $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: page.pagetotal,
                    pageSize: page.pageSize,
                    pageNumber: page.pageNumber
                });
                customizedEasyuiPagination('pp'); //定制化分页
            },
            columns: [[
                 { field: 'ck', width: 120, checkbox: true },
                 { field: 'MATERIALCODE', title: '物料编码', width: 120 },
                 { field: 'MATERIALDESC', title: '物料描述', width: 120 },
		         { field: 'WORKCENTERNAME', title: '中心（部门）', width: 80 }, //--
                 { field: 'TEAMNAME', title: '班组（科室）', width: 90 }, 
                 { field: 'YEAR', title: '年份', width: 90 }, 
                 { field: 'YEARQTY', title: '年度消耗定额', width: 90 }, 
                 { field: 'FULLNAME', title: '创建人', width: 90 },  
                 { field: 'CREATEDATE', title: '最后修改时间', width: 150} 
	           ]],
          onSelect: function (index, row) {
                 //if(!$('#TeamIDD').hasClass('l-btn-disabled')){}
                 $('#TeamIDD').combobox('readonly');
                 $('#year').combobox('readonly');
                 $('#WorkcenterIDD').combobox('readonly');
                 $('#MATERIALCODE').combobox('readonly');
                 page.GetMonthConsumeQuota();
                 $('#EditerForm').form('load', row);
                 $("#yearTable").datagrid("uncheckAll").datagrid("checkRow",index);
            },
          onUncheck:function(){page.GetMonthConsumeQuota();page.ClearYearAndMonth();},
          onUncheckAll:function(){page.GetMonthConsumeQuota(); },
          onCheckAll:function(){
                page.GetMonthConsumeQuota();
                $("#yearTable").datagrid("clearSelections");
                page.ClearYearAndMonth();
          },
          onCheck:function(rowIndex,rowData){
                page.GetMonthConsumeQuota();
                var checkRows= $("#yearTable").datagrid("getChecked");
                var selectRow= $("#yearTable").datagrid("getSelected");
                if(checkRows.length>1){
                    $("#yearTable").datagrid("clearSelections");
                    $('#EditerForm').form("clear");
                }
            }
        });
         $("#monthTable").datagrid({
            checkOnSelect: false,
            selectOnCheck: false,
            singleSelect: true,
            rownumbers: true,
          columns: [[
                 { field: 'ck', width: 120, checkbox: true },
                 { field: 'MONTH', title: '月份', width: 50 }, 
                 { field: 'MONTHQTY', title: '月消耗定额', width: 90 }, 
                 { field: 'FULLNAME', title: '创建人', width: 90 },  
                 { field: 'CREATEDATE', title: '最后修改时间', width:  150},
                 { field: 'NOTES', title: '备注说明', width: 150}  
	           ]],
          onSelect: function (index, row) {
                 $('#month').combobox('readonly');
                 $('#EditerForm').form('load',{ZSNOTPRODUCTMATERIALDETAILID:row.ZSNOTPRODUCTMATERIALDETAILID,MONTH:row.MONTH,MONTHQTY:row.MONTHQTY,NOTES:row.NOTES});
                 $("#monthTable").datagrid("uncheckAll").datagrid("checkRow",index);
            },
          onCheckAll:function(){
                $("#monthTable").datagrid("clearSelections");
             $('#EditerForm').form('load',{ZSNOTPRODUCTMATERIALDETAILID:'',MONTH:'',MONTHQTY:'',NOTES:''});
          },
          onCheck:function(rowIndex,rowData){
                var checkRows= $("#monthTable").datagrid("getChecked");
                var selectRow= $("#monthTable").datagrid("getSelected");
                if(checkRows.length>1){
                    $("#monthTable").datagrid("clearSelections");
                    $('#EditerForm').form('load',{ZSNOTPRODUCTMATERIALDETAILID:'',MONTH:'',MONTHQTY:'',NOTES:''});
                }
            }
         });
        //分页事件
        $('#pp').pagination({
            onSelectPage: function (pageNumber, pageSize) {
                customizedEasyuiPagination('pp'); //定制化分页
                page.pageSize = pageSize; page.pageNumber = pageNumber;
                page.GetYearConsumeQuota();
            }
        });
        //绑定分页go按钮
        $('#pageGo').on("click", function () {
            var pageNumber = $(this).parents('tr').find('.pagination-num').val();
            page.pageNumber = pageNumber;
            page.GetYearConsumeQuota();
        });
        //清除按钮
        $('#btnReset').on("click", function () {
            page.reset(true, true);
            page.pageNumber = 1; page.pagetotal = 0
            $('#pp').pagination('refresh', {
                total: page.pagetotal,
                pageSize: page.pageSize,
                pageNumber: page.pageNumber
            });
        });
    },
    //查询
    searchData: function () {
        page.reset(false, true);
        page.pageNumber = 1;
        page.GetYearConsumeQuota();
         $('#EditerForm').form("clear");
    },
    InitWorkcenterCombox:function(res,id){
     $(id).combobox({
                data: res,
                valueField: 'WORKCENTERID',
                textField: 'WORKCENTERNAME',
                onSelect: function (record) {
                    if(id=="#WorkcenterID"){
                        page.GetTeamByWorkcenter(record.WORKCENTERID,"#TeamID");
                    }else{
                        page.GetTeamByWorkcenter(record.WORKCENTERID,"#TeamIDD");
                    }
                }
            });
    
    },
    GetTeamByWorkcenter:function(WorkcenterID,itemid){
     page.post({action:"GetTeamByWorkcenter",workcenterId:WorkcenterID}, function (res) {
            $(itemid).combobox({
                data: res,
                valueField: 'TEAMID',
                textField: 'TEAMNAME',
                onSelect: function (record) {
                     
                }
            });

            var row= $('#yearTable').datagrid('getSelected')
            if(row!=null){
                     $(itemid).combobox('setValue',row.TEAMID);
                     }
        });
    },
    //查询材料申领单信息
    GetYearConsumeQuota: function () {
        $('#monthTable').datagrid('loadData',[]);
        var frdata = $('#searchForm').serializeArray();
        var data = {};
        $.each(frdata, function () {
            data[this.name] = this.value
        });
        var param = {
            action: "GetYearConsumeQuota",
            pageSize: page.pageSize,
            pageNumber: page.pageNumber,
            data: JSON.stringify([data])
        };
        page.post(param, function (res) {
            if (res.Result) {
                //console.info(res);
                page.pagetotal = res.RowCount;
                $('#yearTable').datagrid('loadData', res.DBTable);
            }
        });
    },
    GetMonthConsumeQuota:function(){
        var rows=$('#yearTable').datagrid("getChecked");
        if(rows.length==0){ $('#monthTable').datagrid('loadData', []);return;}
        var data = [];
        $.each(rows, function (index,item) {
           data.push(item.ZSNOTPRODUCTMATERIALID);
        });
        var param = {
            action: "GetMonthConsumeQuota",
            ids: data.join(',')
        };
        page.post(param, function (res) {
            $('#monthTable').datagrid('loadData', res.DBTable);
        });
    
    },
    AddYearAndMonth:function(index){
        var frdata = $('#EditerForm').serializeArray();
        var data = {};
        $.each(frdata, function () {
            data[this.name] = this.value
        });
        var param = {
            action: "AddYearAndMonth",
            Type:index,
            data: JSON.stringify([data])
        };
        if(index==0){
            if(data.YEAR==""){ displayMessage("年份不能为空，请选择",false);return;}
            if(data.WORKCENTERID==""){ displayMessage("中心（部门）不能为空，请选择",false);return;}
            if(data.MATERIALCODE==""){ displayMessage("物料编码不能为空，请选择",false);return;}
            if(data.MATERIALDESC==""){ displayMessage("物料描述不能为空，请选择",false);return;}
            if(data.YEARQTY==""){ displayMessage("年消耗定额不能为空，请输入",false);return;}
            var yearRows= $('#yearTable').datagrid('getRows');
            var isExist =yearRows.some(function (i){
                      if(i.YEAR == data.YEAR&&i.TEAMID==data.TEAMID&&i.MATERIALCODE==data.MATERIALCODE){
                        return true;
                      }
                })
                if (isExist) {
                  displayMessage(data.YEAR+"年"+$('#TeamIDD').combobox('getText')+"物料【"+data.MATERIALCODE+"】消耗定额已维护数据",false);return;
                }
        }
        if(index==1){
            if(data.ZSNOTPRODUCTMATERIALID==""){ displayMessage("请选择年消耗定额记录，再进行月消耗定额维护",false);return;}
            if(data.MONTH==""){ displayMessage("月份不能为空，请选择",false);return;}
            if(data.MONTHQTY==""){ displayMessage("月消耗定额不能为空，请输入",false);return;}
            var monthRows= $('#monthTable').datagrid('getRows');
            var isExist = monthRows.some(function (i) {
                    if(i.MONTH == data.MONTH){return true;}
                })
                if (isExist) {
                  displayMessage(data.YEAR+"年已维护"+data.MONTH+"月数据",false);return;
                }
        }
        page.post(param, function (res) {
            if (res.Result) {
                if(index==0){
                   page.GetYearConsumeQuota();
                   page.ClearYearAndMonth();
                }else{
                   page.GetMonthConsumeQuota();
                   $('#EditerForm').form('load',{ZSAUXMATERIALMONTHCONQUOTAID:'',MONTH:'',MONTHQTY:'',NOTES:''});
                }
               
            }
            displayMessage(res.Message,res.Result);
        });
    },
    UpdateYearAndMonth:function(){
        var frdata = $('#EditerForm').serializeArray();
        var data = {};
        $.each(frdata, function () {
            data[this.name] = this.value
        });
        var param = {
            action: "UpdateYearAndMonth",
            Type:'',
            data: JSON.stringify([data])
        };
        page.post(param, function (res) {
            if (res.Result) {
                if(data.ZSNOTPRODUCTMATERIALID!=""&&data.ZSNOTPRODUCTMATERIALDETAILID==""){
                    page.GetYearConsumeQuota();
                }else if(data.ZSNOTPRODUCTMATERIALID==""&&data.ZSNOTPRODUCTMATERIALDETAILID!=""){
                  page.GetMonthConsumeQuota();
                } else{
                   page.GetYearConsumeQuota();
                   page.GetMonthConsumeQuota();
                  }
                }
            displayMessage(res.Message,res.Result);
        });
    },
    DeleteYearAndMonth:function(type){
       var yearRows=$('#yearTable').datagrid("getChecked");
       var monthRows=$('#monthTable').datagrid("getChecked");
       if(yearRows.length==0&&type==0){ displayMessage("请勾选年消耗定额记录再进行操作",false);return;}
       if(monthRows.length==0&&type==1){ displayMessage("请勾选月消耗定额记录再进行操作",false);return;}
       var month=[],year=[];
       $.each(yearRows,function(index,item){
            year.push(item.ZSNOTPRODUCTMATERIALID);
       });
       $.each(monthRows,function(index,item){
            month.push(item.ZSNOTPRODUCTMATERIALDETAILID);
       });
       var param = {
           action: "DeleteYearAndMonthConsumeQuota",
           type:type,
           mids:year.join(','),
           ids:month.join(',')
        };
        if(type==0){
           $.messager.confirm('提示', '删除年消耗定额数据，月消耗定额也会删除，是否继续？', function (r) {
                if (r)//继续执行
                {
                   page.DeleteData(param,year,month);
                }
            });
        }else{
            page.DeleteData(param,year,month);
        }
        
    },
    DeleteData:function(param,year,month){
        page.post(param, function (res) {
            if (res.Result) {
                if(year.length>0&&month.length==0){
                    page.GetYearConsumeQuota();
                }else if(year.length==0&&month.length>0){
                  page.GetMonthConsumeQuota();
                } else{
                   page.GetYearConsumeQuota();
                   page.GetMonthConsumeQuota();
                  }
                }
            displayMessage(res.Message,res.Result);
        });
    },
    ClearYearAndMonth:function(){ 
         $("#yearTable").datagrid("clearSelections");
         $('#EditerForm').form('clear');
         $('#TeamIDD').combobox('readonly',false);
         $('#year').combobox('readonly',false);
         $('#WorkcenterIDD').combobox('readonly',false);
         $('#MATERIALCODE').combobox('readonly',false);
         
    },
    //查询重置
    searchReset: function () {
        $('#searchForm').form('clear');
        //page.bind();
    },

    //清除方法，重要！！！
    reset: function (iscondition, isresult) {
        clearMessage();
    },
    //post数据
    post: function (param, callback) {
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: param,
            cashe: false,
            async: true,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                $.messager.progress('close');
                callback(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                displayMessage(XMLHttpRequest.responseText, false);
            }
        });
    }
}
$(function () {
    page.init();
});